var obsidian = require('obsidian');
const DEFAULT_SETTINGS = {
    
};
console.log("scroll-dataView is loading...")
//设置图标
// console.log(MyPlugin.settings)
let leftLeaf
let divHeads


//一直询问 直到替换好图标
var searcher = null;   //定义时间器
var i = 0; 
clearInterval(searcher); //先清空时间器
searcher = setInterval(function () {
    leftLeaf=document.getElementsByClassName('mod-left-split')
    if(leftLeaf[0]){
        divHeads=leftLeaf[0].getElementsByClassName("workspace-tab-header")
        if(divHeads.length){
            let settings=app.plugins.plugins["obsidian-scroll-dataView"].settings
            for(var i=0;i<divHeads.length;i++){
                let title=divHeads[i].ariaLabel
                let svg=divHeads[i].getElementsByTagName('svg')[0]
                if(settings[title]){
                    svg.setAttribute('class',settings[title])
                }
                
            }
            // console.log(divHeads)
            // console.log(app.plugins.plugins["obsidian-scroll-dataView"].settings)
            clearInterval(searcher)
        }
    }
},500)

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}
function scrollViewFro(){
    let myTitle=app.workspace.activeLeaf.view.file.basename
    let target
    let frontTarget
    let tr

    
    //寻找目标
    let leafs=document.getElementsByClassName('workspace-leaf')
    let tables
    let links
    
    if(leafs.length){
        tables=leafs[0].getElementsByClassName('table-view-table')
        if(tables.length){
            links= tables[0].getElementsByClassName('internal-link')
            for(var i=0;i<links.length;i++){
                if( links[i].innerText==myTitle){
                    target=links[i]
                }
            }
        }
    }
    //找到了
    tr=target?target.parentNode.parentNode.parentNode.previousElementSibling:false
    if(tr){
        
        frontTarget=tr.getElementsByClassName('internal-link')[0]
        //跳转
        frontTarget.click()
        //a:可视区域高度 b:滚动条位置 c:当前行位置 d:当前行高度
        let box=tables[0].parentNode.parentNode.parentNode.parentNode
        let a=document.documentElement.clientHeight
        let b=box.scrollTop
        let c=tr.offsetTop
        let d=tr.offsetHeight
        if(tr&&c>b+d&&c<b+a-d){
            tr.scrollIntoView({
                behavior: 'smooth',
                block: 'center', // could be negative value
                inline: "nearest"
            })
        }else{
            tr.scrollIntoView({
                block: 'center', // could be negative value
                inline: "nearest"
            })
        }
        //滚动视图
        
        //闪烁
        var timer = null;   //定义时间器
        var i = 0; 
        clearInterval(timer); //先清空时间器
        timer = setInterval(function () {
            if(i++ % 2 ){
                tr.removeAttribute('style');
            }else{
                tr.style.backgroundColor="#f00"
            }
            if(i > 2){
                clearInterval(timer)
                tr.removeAttribute('style');
            }
        }, 250 );
        
    }
    
};
function scrollViewLat(){
    let myTitle=app.workspace.activeLeaf.view.file.basename
    let target
    let latterTarget
    let tr

    
    //寻找目标
    let leafs=document.getElementsByClassName('workspace-leaf')
    let tables
    let links
    
    if(leafs.length){
        tables=leafs[0].getElementsByClassName('table-view-table')
        if(tables.length){
            links= tables[0].getElementsByClassName('internal-link')
            for(var i=0;i<links.length;i++){
                if( links[i].innerText==myTitle){
                    target=links[i]
                }
            }
        }
    }
    //找到了
    tr=target?target.parentNode.parentNode.parentNode.nextElementSibling:false
    if(tr){
        latterTarget=tr.getElementsByClassName('internal-link')[0]
        latterTarget.click()
        
        let box=tables[0].parentNode.parentNode.parentNode.parentNode
        let a=document.documentElement.clientHeight
        let b=box.scrollTop
        let c=tr.offsetTop
        let d=tr.offsetHeight
        if(tr&&c>b+d&&c<b+a-d){
            tr.scrollIntoView({
                behavior: 'smooth',
                block: 'center', // could be negative value
                inline: "nearest"
            })
        }else{
            tr.scrollIntoView({
                block: 'center', // could be negative value
                inline: "nearest"
            })
        }
        var timer = null;   //定义时间器
        var i = 0; 
        clearInterval(timer); //先清空时间器
        timer = setInterval(function () {
            if(i++ % 2 ){
                tr.removeAttribute('style');
            }else{
                tr.style.backgroundColor="#f00"
            }
            if(i > 2){
                clearInterval(timer)
                tr.removeAttribute('style');
            }
        }, 250 );
    }
    
};


function scrollView(){
    let myTitle=app.workspace.activeLeaf.view.file.basename
    let target

    
    //寻找目标
    let leafs=document.getElementsByClassName('workspace-leaf')
    let tables
    let links
    
    if(leafs.length){
        tables=leafs[0].getElementsByClassName('table-view-table')
        if(tables.length){
            links= tables[0].getElementsByClassName('internal-link')
            for(var i=0;i<links.length;i++){
                if( links[i].innerText==myTitle){
                    target=links[i]
                }
            }
        }
    }
    //找到了
    if(target){
        //滚动
        let tr=target.parentNode.parentNode.parentNode
        
        let box=tables[0].parentNode.parentNode.parentNode.parentNode
        let a=document.documentElement.clientHeight
        let b=box.scrollTop
        let c=tr.offsetTop
        let d=tr.offsetHeight
        if(tr&&c>b+d&&c<b+a-d){
            tr.scrollIntoView({
                behavior: 'smooth',
                block: 'center', // could be negative value
                inline: "nearest"
            })
        }else{
            tr.scrollIntoView({
                block: 'center', // could be negative value
                inline: "nearest"
            })
        }
        //闪烁
        var timer = null;   //定义时间器
        var i = 0; 
        clearInterval(timer); //先清空时间器
        timer = setInterval(function () {
            if(i++ % 2 ){
                tr.removeAttribute('style');
            }else{
                tr.style.backgroundColor="#f00"
            }
            if(i > 2){
                clearInterval(timer)
                tr.removeAttribute('style');
            }
        }, 250 );
    }
    
};

class MyPlugin extends obsidian.Plugin {
    async onload() {
        await this.loadSettings();
        let settings=app.plugins.plugins["obsidian-scroll-dataView"].settings

        this.addCommand({
            id: 'scroFront',
            name: '前一个文件',
            checkCallback: scrollViewFro
        });
        this.addCommand({
            id: 'scro',
            name: '当前文件',
            callback: scrollView
        });
        this.addCommand({
            id: "scroLat",
            name: "后一个文件",
            checkCallback: scrollViewLat
        });
        this.addSettingTab(new SampleSettingTab(this.app, this));
    }
    async writeOptions(changeOpts) {
        this.settings.update((old) => (Object.assign(Object.assign({}, old), changeOpts(old))));
        await this.saveData(this.options);
    }
    
    loadSettings() {
        return __awaiter(this, void 0, void 0, function* () {
            this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData());
        });
        
    }
    saveSettings(divHeads,title,value) {
        
        for(var i=0;i<divHeads.length;i++){
            let thistitle=divHeads[i].ariaLabel
            if(thistitle==title){
                let svg=divHeads[i].getElementsByTagName('svg')[0]
                svg.setAttribute('class',value)
            }
        }
        return __awaiter(this, void 0, void 0, function* () {
            yield this.saveData(this.settings);
        });
    }
}
class SampleSettingTab extends obsidian.PluginSettingTab {
    constructor(app, plugin) {
        super(app, plugin);
        this.plugin = plugin;
    }


    display() {
        const iconCanBeSeclet =["请选择","默认","any-key", "audio-file", "blocks", "bold-glyph", "bracket-glyph", "broken-link", "bullet-list", "bullet-list-glyph", "calendar-with-checkmark", "check-in-circle", "check-small", "checkbox-glyph", "checkmark", "clock", "cloud", "code-glyph", "create-new", "cross", "cross-in-box", "crossed-star", "csv", "deleteColumn", "deleteRow", "dice", "document", "documents", "dot-network", "double-down-arrow-glyph", "double-up-arrow-glyph", "down-arrow-with-tail", "down-chevron-glyph", "enter", "exit-fullscreen", "expand-vertically", "filled-pin", "folder", "formula", "forward-arrow", "fullscreen", "gear", "go-to-file", "hashtag", "heading-glyph", "help", "highlight-glyph", "horizontal-split", "image-file", "image-glyph", "indent-glyph", "info", "insertColumn", "insertRow", "install", "italic-glyph", "keyboard-glyph", "languages", "left-arrow", "left-arrow-with-tail", "left-chevron-glyph", "lines-of-text", "link", "link-glyph", "logo-crystal", "magnifying-glass", "microphone", "microphone-filled", "minus-with-circle", "moveColumnLeft", "moveColumnRight", "moveRowDown", "moveRowUp", "note-glyph", "number-list-glyph", "open-vault", "pane-layout", "paper-plane", "paused", "pdf-file", "pencil", "percent-sign-glyph", "pin", "plus-with-circle", "popup-open", "presentation", "price-tag-glyph", "quote-glyph", "redo-glyph", "reset", "right-arrow", "right-arrow-with-tail", "right-chevron-glyph", "right-triangle", "run-command", "search", "sheets-in-box", "sortAsc", "sortDesc", "spreadsheet", "stacked-levels", "star", "star-list", "strikethrough-glyph", "switch", "sync", "sync-small", "tag-glyph", "three-horizontal-bars", "trash", "undo-glyph", "unindent-glyph", "up-and-down-arrows", "up-arrow-with-tail", "up-chevron-glyph", "uppercase-lowercase-a", "vault", "vertical-split", "vertical-three-dots", "wrench-screwdriver-glyph"];
        let { containerEl } = this;
        containerEl.empty();

        let leftLeaf
        let divHeads
        leftLeaf=document.getElementsByClassName('mod-left-split')
        divHeads=leftLeaf[0].getElementsByClassName("workspace-tab-header")
        
        for(var i=0;i<divHeads.length;i++){
            let title=divHeads[i].ariaLabel
            let svg=divHeads[i].getElementsByTagName('svg')[0]
            
            let iconClass=svg.classList[0]
            
            new obsidian.Setting(containerEl)
            .setName(title)
            .setDesc(this.plugin.settings[title])
            .addDropdown(dropdown => {
                dropdown.onChange((value) => __awaiter(this, void 0, void 0, function* () {
                    this.plugin.settings[title]= value;
                    yield this.plugin.saveSettings(divHeads,title,value);
                }))
                iconCanBeSeclet.forEach((iconCanBeSeclet) => {//day 数组元素 i索引
                    dropdown.addOption(iconCanBeSeclet,iconCanBeSeclet);//实际值、显示
                })
            });
        }
        
        
    }
}
module.exports = MyPlugin;